package com.mall.service.impl;

import com.mall.common.pojo.EUTreeNode;
import com.mall.common.pojo.TaotaoResult;
import com.mall.mapper.TbContentCategoryMapper;
import com.mall.pojo.TbContentCategory;
import com.mall.pojo.TbContentCategoryExample;
import com.mall.service.ContentCategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class ContentCategoryServiceImpl implements ContentCategoryService{

    @Autowired
    private TbContentCategoryMapper tbContentCategoryMapper;


    @Override
    public List<EUTreeNode> getCategoryList(long parentId) {


        TbContentCategoryExample example=new TbContentCategoryExample();

        TbContentCategoryExample.Criteria criteria=example.createCriteria();
        criteria.andParentIdEqualTo(parentId);

        List<TbContentCategory> list=tbContentCategoryMapper.selectByExample(example);

        List<EUTreeNode> result=new ArrayList<>();
        for (TbContentCategory o:list) {
            EUTreeNode node1=new EUTreeNode();
            node1.setId(o.getId());
            node1.setText(o.getName());
            node1.setState(o.getIsParent()?"closed":"open");
            result.add(node1);
        }

        return result;
    }

    @Override
    public TaotaoResult insertContentCategory(long parentId, String name) {

        TbContentCategory contentCategory=new TbContentCategory();
        contentCategory.setName(name);
        contentCategory.setIsParent(false);
        contentCategory.setStatus(1);
        contentCategory.setParentId(parentId);
        contentCategory.setSortOrder(1);
        contentCategory.setCreated(new Date());
        contentCategory.setUpdated(new Date());
        tbContentCategoryMapper.insert(contentCategory);
        //查看父节点的isParent是否为true，不是的话改成true
        TbContentCategory parentCat=tbContentCategoryMapper.selectByPrimaryKey(parentId);
        if(!parentCat.getIsParent()){
            parentCat.setIsParent(true);
            tbContentCategoryMapper.updateByPrimaryKey(parentCat);
        }

        return TaotaoResult.ok(contentCategory);
    }
}
